package com.hwl.acl.service.impl;

import com.hwl.acl.pojo.User;
import com.hwl.acl.service.PermissionService;
import com.hwl.acl.service.UserService;
import com.hwl.security.entity.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;
    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中取出用户信息
        User user = userService.getUserByName(username);

        //判断用户是否存在
        if (null == user || user.getIsDeleted()) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        com.hwl.security.entity.User curUser = new com.hwl.security.entity.User();
        BeanUtils.copyProperties(user, curUser);

        List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
        SecurityUser securityUser = new SecurityUser(curUser);
        securityUser.setPermissionValueList(authorities);
        //返回UserDetails实现类
        return securityUser;
    }
}
